<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body {
        }
    </style>
</head>
<body>
<section>
    <h1>图片转换成base64</h1>
    <a href="http://www.jb51.net/html5/495901.html">更多详情</a><br>
    <input type="file" id="img_upload"/><br>
    <label for="base64_code">base64编码:</label><textarea id="base64_code" rows="30" cols="360"></textarea><br>
    <label for="img_area">图片img标签展示:</label>
    <p id="img_area"></p>
</section>
<section>
    <h1>相关问题</h1>
    <ul>
        <li><a href="https://segmentfault.com/q/1010000000740464">用户上传的图片大小不一，如何展示同一个规格？</a></li>
    </ul>
</section>
<script type="text/javascript">
    var dImgUpload,
            dBase64Code,
            dImgArea,
            storageImg;
    window.onload = function () {
        // 抓取上传图片，转换代码结果，显示图片的dom
        dImgUpload = document.getElementById("img_upload");
        dBase64Code = document.getElementById("base64_code");
        dImgArea = document.getElementById("img_area");
        storageImg = localStorage.getItem("headImg");
        if (storageImg) {
            // 请求本地
            dImgArea.innerHTML = '<img src="' + storageImg + '" alt=""/>'
        }else{
            // 请求远程
        }
        // 添加功能出发监听事件
        dImgUpload.addEventListener('change', readFile, false);
    };
    function readFile() {
        console.log(this, this.files[0]);
        var file = this.files[0];
        // 最大1M
        var maxSize = 1024 * 1024;
        if (!/image\/\w+/.test(file.type) && file.size < maxSize) {
            alert("请确保文件为图像类型并且不超过1M");
            return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
            dBase64Code.innerHTML = this.result;
            dImgArea.innerHTML = '<img src="' + this.result + '" alt=""/>';
            // 保存到远程
            // 保存到本地 最大不超过5M
            localStorage.setItem("headImg", this.result);
        }
    }
</script>
</body>
</html>